<template>
  <div v-loading="dataLoading" class="app-container">
    <div class="data-content">
      <div class="action-content">
        <el-row :gutter="10">
          <el-col :span="14">
            <span style="font-size: x-large; margin-right: 10px">{{ $t('inboundScan') }}</span>
            <span style="color: grey">{{ $t('inbound.orderNo') }} {{ orderInfo.orderNo }}</span>
            <br><br>
            <span style="color: red">{{ $t('inbound.warning') }}</span>
          </el-col>
          <el-col :span="9">
            <el-button :disabled="currentTab === '1' || selectedList.length === 0" type="primary" style="float: right" @click="confirmInound">{{ $t('inbound.confirm') }}</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="12">
            <el-input
              ref="skuInput"
              v-model="skuCode"
              :placeholder="$t('inbound.pleaseScanSku')"
              clearable
              @keyup.enter.native.prevent="handleScanSku"
            >
              <i slot="prefix" class="el-icon-full-screen scan-icon" />
            </el-input>
          </el-col>
        </el-row>
      </div>
      <el-tabs v-model="currentTab" @tab-click="handleTabSwitch">
        <el-tab-pane :label="$t('inbound.statusNew')" name="0" />
        <el-tab-pane :label="$t('inbound.statusFinished')" name="1" />
      </el-tabs>
      <div class="table-content">
        <el-table ref="orderTable" :data="tableData" height="100%" style="width: 100%" stripe highlight-current-row @selection-change="handleSelectionChange" @current-change="handleCurrentChange">
          <el-table-column v-if="currentTab === '0'" type="selection" width="55" align="center" />
          <el-table-column type="expand" width="45" align="center">
            <template slot-scope="scope">
              <el-table :data="scope.row.orderInfoBoxSkuDTOList" :show-header="false">
                <el-table-column :width="currentTab === '0'? 100 : 45" align="center" />
                <el-table-column min-width="150" prop="skuCode" align="center" />
                <el-table-column min-width="100" prop="receiveStatus" align="center">
                  <template v-slot="{ row }">
                    {{ row.receiveStatus === 0 ? $t("warehousingLang.firstArrival") : $t("warehousingLang.toTheWarehouseAgain") }}
                  </template>
                </el-table-column>
                <el-table-column min-width="150" prop="packagingType" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ $t('warehousingLang.' + packagingTypeEnum.find(item => item.value === row.packagingType).title) }}</span>
                    <el-select v-else v-model="row.packagingType">
                      <el-option v-for="item in packagingTypeEnum" :key="item.value" :value="item.value" :label="$t('warehousingLang.' + item.title)" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column min-width="250" prop="realSize" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ row.skuLength }}*{{ row.skuWidth }}*{{ row.skuHeight }} CM</span>
                    <el-row v-else :gutter="5">
                      <el-col :span="7"><el-input v-model="row.realLength" /></el-col>
                      <el-col :span="7"><el-input v-model="row.realWidth" /></el-col>
                      <el-col :span="10">
                        <el-input v-model="row.realHeight">
                          <span slot="suffix" class="el-input__icon">CM</span>
                        </el-input>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column prop="realWeight" min-width="100" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ row.skuWeight }} KG</span>
                    <el-input v-else v-model="row.realWeight">
                      <span slot="suffix" class="el-input__icon">KG</span>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="preSkuNum" min-width="100" align="center" />
                <el-table-column prop="receiptNum" min-width="100" align="center">
                  <template v-slot="{ row }">
                    <span v-if="currentTab === '1'">{{ row.receiptNum }}</span>
                    <el-input v-else v-model="row.receiptNum" />
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column :label="$t('inbound.boxNo')" min-width="150" prop="boxNo" align="center" />
          <el-table-column :label="$t('inbound.receiveStatus')" min-width="100" prop="receiveStatus" align="center" />
          <el-table-column min-width="150" prop="packagingType" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.packagingType') }}
            </template>
          </el-table-column>
          <el-table-column min-width="250" prop="realSize" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.realSize') }}
            </template>
            <template slot-scope="scope">
              <span v-if="currentTab === '1'">{{ scope.row.boxLength }}*{{ scope.row.boxWidth }}*{{ scope.row.boxHeight }} CM</span>
              <el-row v-else :gutter="5">
                <el-col :span="7"><el-input v-model="scope.row.boxLength" /></el-col>
                <el-col :span="7"><el-input v-model="scope.row.boxWidth" /></el-col>
                <el-col :span="10">
                  <el-input v-model="scope.row.boxHeight">
                    <span slot="suffix" class="el-input__icon">CM</span>
                  </el-input>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="realWeight" min-width="100" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.realWeight') }}
            </template>
            <template slot-scope="scope">
              <span v-if="currentTab === '1'">{{ scope.row.boxWeight }} KG</span>
              <el-input v-else v-model="scope.row.boxWeight">
                <span slot="suffix" class="el-input__icon">KG</span>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column :label="$t('inbound.forecastNum')" prop="boxPreNum" min-width="100" align="center" />
          <el-table-column prop="receiptNum" min-width="100" align="center">
            <template slot="header">
              <span v-if="currentTab === '0'" style="color: red">*</span>{{ $t('inbound.receiptNum') }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { confirmSkuInound, getOrderInfo } from '@/api/business/warehouseManage/inbound';
import { scanFail, scanSuccess } from '@/utils/validate';
import { packageTypeDict } from '@/utils/dictData';
import getDictOptionList from '@/utils/dictUtils';

export default {
  name: 'SkuInbound',
  components: {},
  data() {
    return {
      dataLoading: false,
      currentTab: '0',
      orderInfo: {},
      boxNo: null,
      skuCode: null,
      packagingTypeEnum: getDictOptionList(packageTypeDict),
      currentBox: null,
      tableData: [],
      selectedList: [],
    }
  },
  created() {
    this.getOrderInfo(this.$route.params.orderNo)
  },
  methods: {
    handleTabSwitch() {
      this.dataLoading = true
      if (this.skuCode) {
        this.tableData = this.orderInfo.orderInfoBoxDTOList.filter(item => {
          if (this.currentTab === '0') {
            return (item.boxStatus === 0 || item.boxStatus === 11 || item.boxStatus === 22)
          } else {
            return (item.boxStatus === 1 || item.boxStatus === 2)
          }
        })
        this.tableData.forEach(item => { item.orderInfoBoxSkuDTOList = item.orderInfoBoxSkuDTOList.filter(sku => sku.skuCode === this.skuCode).filter(sku => sku.receiptNum === 0) })
        this.tableData = this.tableData.filter(item => {
          return (item.orderInfoBoxSkuDTOList.length > 0)
        })
      } else {
        this.tableData = this.orderInfo.orderInfoBoxDTOList.filter(item => {
          if (this.currentTab === '0') {
            return (item.boxStatus === 0 || item.boxStatus === 11 || item.boxStatus === 22)
          } else {
            return (item.boxStatus === 1 || item.boxStatus === 2)
          }
        })
        this.tableData.forEach(item => { item.orderInfoBoxSkuDTOList = item.orderInfoBoxSkuDTOList.filter(sku => sku.receiptNum === 0) })
        this.tableData = this.tableData.filter(item => {
          return (item.orderInfoBoxSkuDTOList.length > 0)
        })
      }
      if (this.currentTab === '0') {
        const selectedListTemp = this.selectedList;
        const currentBoxTemp = this.currentBox;
        this.$nextTick(() => {
          selectedListTemp.forEach(row => this.$refs.orderTable.toggleRowSelection(row, true))
          this.$refs.orderTable.setCurrentRow(currentBoxTemp);
          this.$refs.orderTable.toggleRowExpansion(currentBoxTemp, true);
          this.dataLoading = false
        })
      } else {
        this.dataLoading = false
      }
    },
    scrollToCurrentRow() {
      this.$nextTick(() => {
        this.$refs.orderTable.toggleRowExpansion(this.currentBox, true);
        const currentRow = this.$refs.orderTable.$el.getElementsByClassName('current-row')[0]
        if (currentRow) {
          this.$refs.orderTable.bodyWrapper.scrollTo({ top: currentRow.offsetTop })
        }
      })
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      if (this.currentTab === '0') {
        this.currentBox = currentRow
      }
      this.$refs.orderTable.toggleRowExpansion(currentRow, true);
    },
    handleScanSku() {
      this.currentBox = this.orderInfo.orderInfoBoxDTOList.find(item => item.boxStatus === 0 || item.boxStatus === 11 || item.boxStatus === 22).orderInfoBoxSkuDTOList.filter(item => item.skuCode === this.skuCode)
      if (this.currentBox) {
        scanSuccess()
        this.currentTab = '0'
        // this.selectedList.push(this.currentBox)
        this.handleTabSwitch();
        this.$nextTick(() => {
          this.$refs.skuInput.focus()
          this.scrollToCurrentRow()
        })
      } else {
        this.skuCode = null
        scanFail()
      }
    },
    handleSelectionChange(rows) {
      if (this.currentTab === '0') {
        this.selectedList = rows;
      }
    },
    async getOrderInfo(orderNo) {
      this.dataLoading = true;
      await getOrderInfo({ orderNo: orderNo }).then((res) => {
        this.$refs.skuInput.focus()
        res.data.orderInfoBoxDTOList.forEach(box => {
          box.originalBox = box.originalBox !== 0
          box.orderInfoBoxSkuDTOList.forEach(sku => {
            if (sku.receiveStatus !== 0) {
              sku.realLength = sku.skuLength
              sku.realWidth = sku.skuWidth
              sku.realHeight = sku.skuHeight
              sku.realWeight = sku.skuWeight
            }
          })
        })
        this.orderInfo = res.data;
        this.handleTabSwitch()
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    // validateBox(box) {
    //   return box.boxLength > 0 && box.boxWidth > 0 && box.boxHeight > 0 && box.boxWeight > 0
    // },
    // validateSku(box, sku) {
    //   return box.originalBox || (sku.packagingType != null && sku.realLength > 0 && sku.realWidth > 0 && sku.realHeight > 0 && sku.realWeight > 0 && sku.receiptNum > 0)
    // },
    confirmInound() {
      console.log(this.selectedList)
      if (this.selectedList.length <= 0) return
      const request = {
        fromTerminal: 0,
        orderId: this.orderInfo.orderId,
        orderInfoForReceiptList: []
      }
      for (const box of this.selectedList) {
        // if (!this.validateBox(box)) {
        //   this.$message.error(this.$t('pleaseCheck') + this.$t('required'))
        //   this.$refs.orderTable.setCurrentRow(box);
        //   this.scrollToCurrentRow()
        //   return
        // }
        for (const sku of box.orderInfoBoxSkuDTOList) {
          // if (!this.validateSku(box, sku)) {
          //   this.$message.error(this.$t('pleaseCheck') + this.$t('required'))
          //   this.$refs.orderTable.setCurrentRow(box);
          //   this.scrollToCurrentRow()
          //   return
          // }
          request.orderInfoForReceiptList.push({
            boxId: box.boxId,
            boxLength: box.boxLength,
            boxWidth: box.boxWidth,
            boxHeight: box.boxHeight,
            boxWeight: box.boxWeight,
            skuId: sku.skuId,
            packagingType: sku.packagingType,
            skuLength: sku.realLength,
            skuWidth: sku.realWidth,
            skuHeight: sku.realHeight,
            skuWeight: sku.realWeight,
            receiptNum: sku.receiptNum,
            originalBox: box.originalBox ? 1 : 0,
          })
        }
      }
      this.dataLoading = true;
      confirmSkuInound(request).then((res) => {
        if (!res || res.returnCode !== 10000) return
        this.$confirm(this.$t('inbound.inboundSuccess'), '', {
          confirmButtonText: this.$t('inbound.continuScan'),
          cancelButtonText: this.$t('cancel'),
          type: 'success',
          center: true
        }).then(() => {
          this.$router.push({ name: 'InboundScan' })
          this.confirmInoundSuccess()
        }).catch(() => {
          this.confirmInoundSuccess()
        });
      }).finally(() => {
        this.dataLoading = false;
      })
    },
    confirmInoundSuccess() {
      this.boxNo = null
      this.skuCode = null
      this.currentTab = '1'
      this.currentBox = null
      this.selectedList = []
      this.getOrderInfo(this.orderInfo.orderNo)
      this.$nextTick(() => {
        this.$refs.orderTable.clearSelection();
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: auto;
}

.data-content{
  padding: 20px;
  flex: 1;
  border: 1px solid #e6ebf5;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  display: flex;
  flex-direction: column;
  min-height: 500px;
  overflow: hidden;

  .action-content {
    margin-bottom: 5px;

    ::v-deep .el-input__inner {
      height: 50px;
      padding-left: 45px;
    }

    .scan-icon {
      margin: 15px 15px 0 10px;
      font-size: 20px
    }
  }

  .table-content {
    flex: 1;
    overflow: hidden;
  }
}
</style>
